#!/usr/bin/env perl

use FindBin;
use lib $FindBin::Bin;
use lib "$FindBin::Bin/../lib";
use lib "$FindBin::Bin/../pllib/lib/perl5";

use strict;
use File::Basename;
use Getopt::Long;
use JSON;

use AutoExecUtils;

sub usage {
    my $pname = basename($0);

    print("Usage: $pname --message <message>\n");

    exit(1);
}

sub main {
    my ( $title, $opType, $message, $options, $role );

    GetOptions( 'message=s' => \$message );

    $title   = 'Continue';
    $opType  = 'button';
    $options = [ 'Yes', 'No' ];

    my $rc = 0;

    my $hasOptError = 0;

    if ( not defined($message) ) {
        $hasOptError = 1;
        print("ERROR: Must defined option message.\n");
    }

    my $nodeInfo;
    my $nodeJson = $ENV{AUTOEXEC_NODE};
    if ( defined($nodeJson) and $nodeJson ne '' ) {
        $nodeInfo = from_json($nodeJson);
    }

    if ( not defined($nodeInfo) ) {
        $hasOptError = 1;
        print("ERROR: Must define node info environment varialble AUTOEXEC_NODE in json string.\n");
    }

    my $jobPath = $ENV{AUTOEXEC_WORK_PATH};
    if ( not defined($jobPath) or $jobPath eq '' ) {
        $jobPath = getcwd();
    }
    my $phaseName = $ENV{AUTOEXEC_PHASE_NAME};
    if ( not defined($phaseName) or $phaseName eq '' ) {
        $hasOptError = 1;
        print("WARN: PhaseName not defined, must define environment variable AUTOEXEC_PHASE_NAME.\n");
        $phaseName = 'run';
    }

    if ( $hasOptError == 1 ) {
        usage();
    }

    if ( not defined( $nodeInfo->{resourceId} ) ) {
        $nodeInfo->{resourceId} = 0;
    }

    my $pipeFile = AutoExecUtils::getNodePipeFile( $jobPath, $phaseName, $nodeInfo );

    AutoExecUtils::informNodeWaitInput(
        phaseName  => $phaseName,
        resourceId => $nodeInfo->{resourceId},
        title      => $title,
        opType     => $opType,
        message    => $message,
        options    => $options,
        role       => $role,
        pipeFile   => $pipeFile
    );

    my ( $userId, $enter );
    my $hasPrivilege = 0;
    while ( $hasPrivilege == 0 ) {
        ( $userId, $enter ) = AutoExecUtils::doInteract(
            title    => $title,
            opType   => $opType,
            message  => $message,
            options  => $options,
            role     => $role,
            pipeFile => $pipeFile
        );

        if ( not defined($role) or $role eq '' ) {
            $hasPrivilege = 1;
            last;
        }
        if ( defined($userId) and $userId ne '' ) {
            $hasPrivilege = AutoExecUtils::checkInteractPrivilege( $userId, $role );
        }

        print("WARN: You do not has interact privileges.\n");
    }

    AutoExecUtils::informNodeWaitInput(
        phaseName  => $phaseName,
        resourceId => $nodeInfo->{resourceId},
        clean      => 1
    );

    my $out = {};

    $out->{interactOut} = $enter;
    AutoExecUtils::saveOutput($out);

    if ($enter ne 'Yes'){
        $rc = 1;
    }
    
    return $rc;
}

exit main();

